#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e5;
typedef long long LL;
LL qpow(LL a,LL n)
{
	LL ans=1;
	while(n)
	{
		if(n&1) ans*=a;
		a*=a;
		n>>=1;
	}
	return ans;
}
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  LL t;cin>>t;
  while(t--){
    LL p,q;cin>>p>>q;
    if(p%q!=0){
        cout<<p<<endl;
    }
    else{
    LL x=p;
    LL ans=0x3f3f3f3f3f3f3f3f;
	for(LL i=2;i*i<=q;i++)
	{
		if(q%i) continue;
		LL c1=0,c2=0;
		while(q%i==0)
		{
			c1++;
			q/=i;
		}
		while(p%i==0)
		{
			c2++;
			p/=i;
		}
		ans=min(ans,qpow(i,c2-c1+1));
	}
	if(q>1)
	{
		LL i=q;
		LL c1=0,c2=0;
		while(q%i==0)
		{
			c1++;
			q/=i;
		}
		while(p%i==0)
		{
			c2++;
			p/=i;
		}
		ans=min(ans,qpow(i,c2-c1+1));
        }
        cout<<x/ans<<endl;
    }

  }
return 0;
}
